package br.ufu.facom.calendar;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.DatePicker;

public class DatePickerFragment extends DialogFragment implements
		DatePickerDialog.OnDateSetListener {
//
	private DateTimeHandler dt;
	private String title;
	private DatePickerDialog dp;

	public void setDateTimeHandler(DateTimeHandler dt) {
		this.dt = dt;
		if (this.dp != null) {
			Calendar c = this.dt.getCalendar();
			dp.updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
					c.get(Calendar.DAY_OF_MONTH));
		}
	}

	public void setTitle(String title) {
		this.title = title;
		if (this.dp != null)
			this.dp.setTitle(this.title);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		Log.d(this.getClass().getCanonicalName(), "onCreateDialog");
		// Use the current date as the default date in the picker
		final Calendar c;
		if (this.dt != null)
			c = this.dt.getCalendar();
		else
			c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		Log.d(this.getClass().getCanonicalName(), "onCreateDialog " + year
				+ "-" + (month + 1) + "-" + day);
		// Create a new instance of DatePickerDialog and return it
		this.dp = new DatePickerDialog(getActivity(), this, year, month, day);
		if (this.title != null)
			this.dp.setTitle(this.title);
		return this.dp;
	}

	public void onDateSet(DatePicker view, int year, int month, int day) {
		// Do something with the date chosen by the user
		if (this.dt != null)
			this.dt.setDate(view);
	}
}
